package servlet;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.servlet.ServletRequestContext;

import session.UserDao;
import utility.ResizeImage;
import entity.User;

/**
 * Kontroler koji vrši registraciju korisnika.
 * @author en_e
 *
 */
public class Register extends HttpServlet {

	private static final long serialVersionUID = 1L;
	@EJB
	private UserDao userDao;

	@SuppressWarnings("unchecked")
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			String email = request.getParameter("email");
			String passwd1 = request.getParameter("passwd1");
			String passwd2 = request.getParameter("passwd2");
			String firstName = request.getParameter("firstName");
			String lastName = request.getParameter("lastName");
			String telNo = request.getParameter("telNo");
			String avatar = null;
			HashMap<String, String> fieldValues = new HashMap<String, String>();
			ServletRequestContext ctx = new ServletRequestContext(request);
			if (ServletFileUpload.isMultipartContent(ctx)) {
				try {
					// Create a factory for disk-based file items
					DiskFileItemFactory factory = new DiskFileItemFactory();
					// Set factory constraints
					factory.setSizeThreshold(2000000);
					// Create a new file upload handler
					ServletFileUpload upload = new ServletFileUpload(factory);
					// Set overall request size constraint
					upload.setSizeMax(3000000);
					// Parse the request
					List items = upload.parseRequest(request);
					// Process the uploaded items
					Iterator iter = items.iterator();
					while (iter.hasNext()) {
						FileItem item = (FileItem) iter.next();
						if (item.isFormField()) {
							String name = item.getFieldName();
							String value = item.getString();
							fieldValues.put(name, value);
						} else {
							if(item!=null) {
								String contentType = item.getContentType();
								String ext = "";
								if (contentType.equalsIgnoreCase("image/gif")) {
									ext = ".gif";
								} else if (contentType
										.equalsIgnoreCase("image/jpeg")) {
									ext = ".jpg";
								} else if (contentType
										.equalsIgnoreCase("image/png")) {
									ext = ".png";
								} else {
									item.delete();
									continue;
								}
								String fileName = UUID.randomUUID().toString()
										+ ext;
								long sizeInBytes = item.getSize();
								if (sizeInBytes != 0) {
									File uploadedFile = new File(
											getServletContext().getRealPath("")
													+ "/avatar/" + fileName);
									item.write(uploadedFile);
									ResizeImage.Resize(uploadedFile, 80, 80);
									avatar = fileName;
								}
							}
						}
					}
				} catch (Exception ex) {
					System.out.println("Upload failed!");
				}
				email = fieldValues.get("email");
				passwd1 = fieldValues.get("passwd1");
				passwd2 = fieldValues.get("passwd2");
				firstName = fieldValues.get("firstName");
				lastName = fieldValues.get("lastName");
				telNo = fieldValues.get("telNo");
			}

			if (email == null || "".equalsIgnoreCase(email.trim())) {
				request.setAttribute("error", "regfailed");
				getServletContext().getRequestDispatcher("/registration.jsp").forward(request, response);
				return;
			}
			if(userDao.isUserExists(email)) {
				request.setAttribute("error", "regfailed");
				getServletContext().getRequestDispatcher("/registration.jsp").forward(request, response);
				return;
			}
			if (passwd1 == null || "".equalsIgnoreCase(passwd1.trim())) {
				request.setAttribute("error", "regfailed");
				getServletContext().getRequestDispatcher("/registration.jsp").forward(request, response);
				return;
			}
			if (passwd2 == null || "".equalsIgnoreCase(passwd2.trim())) {
				request.setAttribute("error", "regfailed");
				getServletContext().getRequestDispatcher("/registration.jsp").forward(request, response);
				return;
			}
			if (!passwd1.equalsIgnoreCase(passwd2)) {
				request.setAttribute("error", "regfailed");
				getServletContext().getRequestDispatcher("/registration.jsp").forward(request, response);
				return;
			}
			if (firstName == null || "".equalsIgnoreCase(firstName.trim())) {
				request.setAttribute("error", "regfailed");
				getServletContext().getRequestDispatcher("/registration.jsp").forward(request, response);
				return;
			}
			if (lastName == null || "".equalsIgnoreCase(lastName.trim())) {
				request.setAttribute("error", "regfailed");
				getServletContext().getRequestDispatcher("/registration.jsp").forward(request, response);
				return;
			}
			if (telNo == null || "".equalsIgnoreCase(telNo.trim())) {
				request.setAttribute("error", "regfailed");
				getServletContext().getRequestDispatcher("/registration.jsp").forward(request, response);
				return;
			}
			if(avatar==null) {
				avatar="default.gif";
			}
			
			User user = new User();
			user.setEmail(email);
			user.setPassword(passwd1);
			user.setFirstName(firstName);
			user.setLastName(lastName);
			user.setPhone(telNo);
			user.setAvatar(avatar);
			user.setType('K');
			user.setActive(false);
			user.setDeleted(false);
			user.setGoals(0);
			userDao.persist(user);

			getServletContext().getRequestDispatcher("/registrationSuccesful.jsp").forward(
					request, response);
			return;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
}
